package com.zzyl.nursing.service.impl;

import java.time.LocalDateTime;
import java.util.List;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.date.DateUtil;
import cn.hutool.core.util.ObjectUtil;
import com.alibaba.fastjson2.JSON;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.zzyl.common.utils.CodeGenerator;
import com.zzyl.common.utils.DateUtils;
import com.zzyl.nursing.domain.*;
import com.zzyl.nursing.dto.CheckInApplyDto;
import com.zzyl.nursing.dto.CheckInConfigDto;
import com.zzyl.nursing.dto.CheckInContractDto;
import com.zzyl.nursing.dto.CheckInElderDto;
import com.zzyl.nursing.mapper.*;
import com.zzyl.nursing.vo.CheckInConfigVo;
import com.zzyl.nursing.vo.CheckInDetailVo;
import com.zzyl.nursing.vo.CheckInElderVo;
import com.zzyl.nursing.vo.ElderFamilyVo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.zzyl.nursing.service.ICheckInService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.transaction.annotation.Transactional;

import java.util.Arrays;

/**
 * 入住Service业务层处理
 * 
 * @author zzyl
 * @date 2025-10-16
 */
@Service
public class CheckInServiceImpl extends ServiceImpl<CheckInMapper, CheckIn> implements ICheckInService
{
    @Autowired
    private CheckInMapper checkInMapper;
    @Autowired
    private ElderMapper elderMapper;
    @Autowired
    private BedMapper bedMapper;
    @Autowired
    private CheckInConfigMapper checkInConfigMapper;
    @Autowired
    private ContractMapper contractMapper;

    /**
     * 查询入住
     * 
     * @param id 入住主键
     * @return 入住
     */
    @Override
    public CheckIn selectCheckInById(Long id)
    {
        return getById(id);
    }

    /**
     * 查询入住列表
     * 
     * @param checkIn 入住
     * @return 入住
     */
    @Override
    public List<CheckIn> selectCheckInList(CheckIn checkIn)
    {
        return checkInMapper.selectCheckInList(checkIn);
    }

    /**
     * 新增入住
     * 
     * @param checkIn 入住
     * @return 结果
     */
    @Override
    public int insertCheckIn(CheckIn checkIn)
    {
        return save(checkIn) ? 1 : 0;
    }

    /**
     * 修改入住
     * 
     * @param checkIn 入住
     * @return 结果
     */
    @Override
    public int updateCheckIn(CheckIn checkIn)
    {
        return updateById(checkIn) ? 1 : 0;
    }

    /**
     * 批量删除入住
     * 
     * @param ids 需要删除的入住主键
     * @return 结果
     */
    @Override
    public int deleteCheckInByIds(Long[] ids)
    {
        return removeByIds(Arrays.asList(ids)) ? 1 : 0;
    }

    /**
     * 删除入住信息
     * 
     * @param id 入住主键
     * @return 结果
     */
    @Override
    public int deleteCheckInById(Long id)
    {
        return removeById(id) ? 1 : 0;
    }

    /**
     * 申请入住
     *
     * @param checkInApplyDto
     */
    @Transactional
    @Override
    public void apply(CheckInApplyDto checkInApplyDto) {

        // 1、校验老人是否已入住
        Elder elder = elderMapper.selectOne(Wrappers.<Elder>lambdaQuery()
                .eq(Elder::getIdCardNo, checkInApplyDto.getCheckInElderDto().getIdCardNo())
                .eq(Elder::getStatus, 1));
        if (ObjectUtil.isNotEmpty(elder)) {
            throw new RuntimeException("该老人已入住");
        }

        // 2、更新床位状态已入住
        CheckInConfigDto checkInConfigDto = checkInApplyDto.getCheckInConfigDto();
        Bed bed = bedMapper.selectById(checkInConfigDto.getBedId());
        bed.setBedStatus(1);
        bedMapper.updateById(bed);

        // 3、新增或更新老人信息
        elder = saveOrUpdateElder(checkInApplyDto, bed);

        // 4、新增签约办理
        saveContract(checkInApplyDto, elder);

        // 5、新增入住信息
        Long checkInId = saveCheckIn(checkInApplyDto, elder);

        // 6、新增入住配置
        saveCheckInConfig(checkInApplyDto, checkInId);
    }

    /**
     * 获取入住详情
     *
     * @param id
     * @return
     */
    @Override
    public CheckInDetailVo detail(Long id) {

        CheckInDetailVo checkInDetailVo = new CheckInDetailVo();

        // 1、查询入住信息
        CheckIn checkIn = checkInMapper.selectById(id);

        // 2、查询老人信息
        Elder elder = elderMapper.selectById(checkIn.getElderId());
        CheckInElderVo checkInElderVo = BeanUtil.toBean(elder, CheckInElderVo.class);
//        String birthday = checkInElderVo.getBirthday();
//        String[] dates = birthday.split("-");
//        String[] nows = DateUtils.getDate().split("-");
//        int age = 0;
//        if (Integer.parseInt(dates[1]) == Integer.parseInt(nows[1])) {
//            if (Integer.parseInt(dates[2]) > Integer.parseInt(nows[1])) {
//                age = Integer.parseInt(nows[0]) - Integer.parseInt(dates[0]) - 1;
//            } else {
//                age = Integer.parseInt(nows[0]) - Integer.parseInt(dates[0]);
//            }
//        } else if (Integer.parseInt(dates[1]) < Integer.parseInt(nows[1])) {
//            age = Integer.parseInt(nows[0]) - Integer.parseInt(dates[0]);
//        } else {
//            age = Integer.parseInt(nows[0]) - Integer.parseInt(dates[0]) - 1;
//        }
        checkInElderVo.setAge(DateUtil.ageOfNow(checkInElderVo.getBirthday()));
        checkInDetailVo.setCheckInElderVo(checkInElderVo);

        // 3、查询合同
        Contract contract = contractMapper.selectOne(Wrappers.<Contract>lambdaQuery().eq(Contract::getElderId, elder.getId()));
        checkInDetailVo.setContract(contract);

        // 4、查询入住配置
        CheckInConfig checkInConfig = checkInConfigMapper.selectOne(Wrappers.<CheckInConfig>lambdaQuery().eq(CheckInConfig::getCheckInId, id));
        CheckInConfigVo checkInConfigVo = BeanUtil.toBean(checkInConfig, CheckInConfigVo.class);
        checkInConfigVo.setStartDate(checkIn.getStartDate());
        checkInConfigVo.setEndDate(checkIn.getEndDate());
        checkInConfigVo.setBedNumber(checkIn.getBedNumber());
        checkInDetailVo.setCheckInConfigVo(checkInConfigVo);

        // 5、转换家属列表
        String remarkJson = checkIn.getRemark();
        List<ElderFamilyVo> elderFamilyVos = JSON.parseArray(remarkJson, ElderFamilyVo.class);
        checkInDetailVo.setElderFamilyVoList(elderFamilyVos);

        // 6、整合数据返回
        return checkInDetailVo;
    }

    /**
     * 新增入住配置
     * @param checkInApplyDto
     */
    private void saveCheckInConfig(CheckInApplyDto checkInApplyDto, Long checkInId) {
        CheckInConfigDto checkInConfigDto = checkInApplyDto.getCheckInConfigDto();
        CheckInConfig checkInConfig = BeanUtil.toBean(checkInConfigDto, CheckInConfig.class);
        checkInConfig.setCheckInId(checkInId);
        checkInConfigMapper.insert(checkInConfig);
    }

    /**
     * 新增入住信息
     * @param checkInApplyDto
     */
    private Long saveCheckIn(CheckInApplyDto checkInApplyDto, Elder elder) {
        CheckInConfigDto checkInConfigDto = checkInApplyDto.getCheckInConfigDto();
        CheckIn checkIn = BeanUtil.toBean(checkInConfigDto, CheckIn.class);
        checkIn.setElderName(elder.getName());
        checkIn.setElderId(elder.getId());
        checkIn.setIdCardNo(elder.getIdCardNo());
        checkIn.setBedNumber(elder.getBedNumber());
        checkIn.setRemark(JSON.toJSONString(checkInApplyDto.getElderFamilyDtoList()));
        checkIn.setStatus(0);
        checkInMapper.insert(checkIn);
        return checkIn.getId();
    }

    /**
     * 新增签约办理
     * @param checkInApplyDto
     */
    private void saveContract(CheckInApplyDto checkInApplyDto, Elder elder) {
        CheckInContractDto checkInContractDto = checkInApplyDto.getCheckInContractDto();
        Contract contract = BeanUtil.toBean(checkInContractDto, Contract.class);
        contract.setElderId(Integer.parseInt(elder.getId() + ""));
        contract.setElderName(elder.getName());
        contract.setContractNumber("HT" + CodeGenerator.generateContractNumber());
        LocalDateTime startDate = checkInApplyDto.getCheckInConfigDto().getStartDate();
        LocalDateTime endDate = checkInApplyDto.getCheckInConfigDto().getEndDate();
        contract.setStartDate(startDate);
        contract.setEndDate(endDate);
        contract.setStatus(startDate.isBefore(LocalDateTime.now()) ? 1 : 0);

        contractMapper.insert(contract);

    }

    /**
     * 新增或更新老人信息
     * @param checkInApplyDto
     */
    private Elder saveOrUpdateElder(CheckInApplyDto checkInApplyDto, Bed bed) {
        CheckInElderDto checkInElderDto = checkInApplyDto.getCheckInElderDto();
        Elder oldElder = BeanUtil.toBean(checkInElderDto, Elder.class);
        oldElder.setStatus(1);
        oldElder.setBedNumber(bed.getBedNumber());
        oldElder.setBedId(bed.getId());
        Elder newElder = elderMapper.selectOne(Wrappers.<Elder>lambdaQuery()
                .eq(Elder::getIdCardNo, checkInElderDto.getIdCardNo())
                .ne(Elder::getStatus, 1));
        if (ObjectUtil.isNotEmpty(newElder)) {
            // 更新老人信息
            elderMapper.updateById(oldElder);
        } else {
            // 新增老人信息
            elderMapper.insert(oldElder);
        }
        return oldElder;
    }
}
